package cn.iocoder.yudao.module.iot.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.iot.model.v20180120.PubRequest;
import com.aliyuncs.iot.model.v20180120.PubResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.UnsupportedEncodingException;

/**
 * desc:工具类，用于服务端下发指令
 * @author:fuzhifei
 * @date:2023/12/18 18:31
 */

@Slf4j
public class AmqpDataDownUtil {


    private final static Logger logger = LoggerFactory.getLogger(AmqpDataDownUtil.class);

    /**
     * desc:服务端下发指令
     * @author:fuzhifei
     * @date:2023/11/27 15:16
     * @param deviceName 设备名称
     * @param jsonStr 下发数据
     * @return boolean 返回操作结果
     */

    public static boolean serverDataDown(String deviceName, String jsonStr) {
        String accessKey = "LTAI5tNBKDJEGVBHzij587QS";
        String accessSecret = "SO2OZUGbkVxRKhrxoRiHJQbn8hzkXh";

        //iotInstanceId：实例ID。若是2021年07月30日之前（不含当日）开通的公共实例，请填空字符串。
        String iotInstanceId = "iot-010a7d09";
        String productKey="k0aivZRsAgr";
        // 指令下发
        DefaultProfile profile = DefaultProfile.getProfile("cn-beijing",
                accessKey, accessSecret);

        IAcsClient client = new DefaultAcsClient(profile);

        PubRequest request = new PubRequest();
        request.setIotInstanceId(iotInstanceId);
        request.setProductKey(productKey);
        String topicName = "/k0aivZRsAgr/" + deviceName + "/user/serverDataDown";
        request.setTopicFullName(topicName);
        Base64 base64 = new Base64();
        final byte[] textByte;
        try {
            textByte = jsonStr.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            logger.error("参数编码失败：", e.toString());
            return false;
        }
        final String encodedText = base64.encodeToString(textByte);
        request.setMessageContent(encodedText);

        try {
            logger.info("云端指令下发参数:" + new Gson().toJson(request));
            PubResponse response = client.getAcsResponse(request);
            logger.info("云端指令下发结果返回返回:" + new Gson().toJson(response));
            JSONObject jsonObject= JSON.parseObject(new Gson().toJson(response));
            String success=jsonObject.getString("success");
            if("true".equals(success)){
                return true;
            }else{
                return false;
            }

        } catch (ClientException e) {
            logger.error("ErrCode:" + e.getErrCode());
            logger.error("ErrMsg:" + e.getErrMsg());
            logger.error("RequestId:" + e.getRequestId());
            logger.error("云端指令下发失败：", e.toString());
            return false;
        }
    }
}
